#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import copy
from testflow import TestFlow
from utils.log import logger
from dispatcher import JobPreDispatcher, JobPostDispatcher


class JobFlow(object):
    def __init__(self, config):
        """
        Job flow init
        """
        logger.debug("Job init")
        self.config = config

    def __enter__(self):
        logger.debug("Job __enter__")
        self.setup()
        return self

    def __exit__(self, _exc_type, _exc_value, _traceback):
        logger.debug("Job __exit__")
        self.cleanup()

    def setup(self):
        """
        setup the env
        """
        logger.debug("Job setup")
        dispatcher = JobPreDispatcher()
        dispatcher.map_method('pre', self)

    def cleanup(self):
        """
        clean env
        """
        logger.debug("Job cleanup")
        dispatcher = JobPostDispatcher()
        dispatcher.map_method('post', self)

    def run(self):
        logger.debug("Run job")
        if self.config.test_list:
            for testconf in self.config.test_list:
                for s in testconf.scenaria[testconf.name]['scenaria']:
                    testconf.current_scenaria = s
                    logger.debug("Run test:{}".format(testconf.name))
                    for _ in range(testconf.current_scenaria['runtimes']):
                        testconf.starttime = time.time()
                        if testconf.timeout:
                            # s['stoptime'] = time.time() + testconf.timeout
                            testconf.stoptime = time.time() + testconf.timeout
                        else:
                            pass
                            # s['stoptime'] = None

                        testconf.var = copy.deepcopy(s['env'])
                        logger.debug("*" * 80)
                        with TestFlow(testconf) as test_instance:
                            test_instance.run()
                        print("\rTest running: Done")
